<?php


namespace App\Http\Controllers\Api;

use App\Businesses\BusinessState;
use App\Http\Requests\ApiV2\ConquerBgImageRequest;
use App\Http\Requests\ApiV2\ConquerRequest;
use App\Services\Business\Models\Conquer;
use App\Services\Business\Models\UserConquer;
use App\Services\Business\Models\WeightFragment;
use App\Services\Company\Models\Process;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Member\Models\Activity;
use App\Services\Member\Models\Socialite;
use App\Services\Member\Models\User;
use App\Services\Member\Services\UserService;
use App\Services\Other\Models\WechatPlatform;
use App\Zesow\WechatMini;
use App\Zesow\WechatOpenPlatform;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;


class ConquerController extends BaseController
{


    /**
     * @var UserService
     */
    protected $userService;

    protected $businessState;


    public function __construct(

        UserServiceInterface $userService,
        BusinessState        $businessState
    )
    {

        $this->userService = $userService;
        $this->businessState = $businessState;

    }


    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request)
    {


        $size = $request->input('size');
        $conquer = Conquer::query()
            ->with(['user:id,nick_name,avatar'])
            ->orderBy('created_at', 'desc')->paginate($size);
        return $this->successData(compact('conquer'));
    }


    public function detail(Request $request, $id)
    {

        $conquer = Conquer::query()->with(['user'])->where('id', $id)->firstOrFail();
        $isAttended = false;
        $isPublishedToday = false;
        $isFollowed = false;
        $isThumbsuped = false;
        $submitCount =  WeightFragment::query()->where('conquer_id', $id)->whereDate('created_at',now()->toDateString())->count();
        if ($this->check()) {
            $isFollowed = $this->userService->isFollowed($this->id(), $conquer->user_id);
            $isAttended = $this->userService->isAttended($id, $this->id());
            $isPublishedToday = $this->userService->isPublishedToday($id, $this->id());
            $isThumbsuped = $this->userService->isThumbsuped($this->id(), $id, Conquer::class);
        }
        $subQuery = DB::table('weight_fragment')
            ->select('user_id', DB::raw('MAX(created_at) as latest_created_at'))
            ->where('conquer_id', $id)
            ->groupBy('user_id');

        //获取每个用户的最新的记录
        $activities = WeightFragment::query()->with('user:id,nick_name,avatar')
            ->joinSub($subQuery, 'latest_activities', function ($join) {
                $join->on('weight_fragment.user_id', '=', 'latest_activities.user_id')
                    ->on('weight_fragment.created_at', '=', 'latest_activities.latest_created_at');
            })
            ->orderByDesc('total_different_weight')
            ->limit(10)
            ->get();

        return $this->successData(compact('conquer', 'isAttended', 'activities', 'isPublishedToday', 'isFollowed', 'isThumbsuped','submitCount'));


    }

    /**
     * 活动未开始
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function detail1(Request $request, $id)
    {


        $conquer = Conquer::query()->with(['user'])->where('id', $id)->firstOrFail();
        $isAttended = false;
        $isFollowed = false;
        $isThumbsuped = false;

        if ($this->check()) {
            $isFollowed = $this->userService->isFollowed($this->id(), $conquer->user_id);
            $isAttended = $this->userService->isAttended($id, $this->id());
            $isThumbsuped = $this->userService->isThumbsuped($this->id(), $id, Conquer::class);
        }
        return $this->successData(compact('conquer', 'isAttended', 'isFollowed', 'isThumbsuped'));

    }

    public function attendUser(Request $request, $id)
    {
        $size = $request->input('size');
        $users = UserConquer::query()->with(['user:id,avatar,nick_name'])->where('conquer_id', $id)->paginate($size);
        return $this->successData(compact('users'));
    }

    /*新增减重
     * @param ConquerRequest $request
     * @param Conquer $conquer
     * @return JsonResponse
     */
    public function store(ConquerRequest $request, Conquer $conquer)
    {


        $userId = $this->id();
        $data = $request->filldata();
        DB::transaction(function () use ($data, $conquer, $userId) {
            $conquer->fill($data)->save();
            $conquer->activity()->save(new Activity(['user_id' => $userId]));
        });
        return $this->successData(compact('conquer'));
    }

    /**挑战编辑
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function edit(Request $request, $id)
    {

        $conquer = Conquer::query()
            ->where('id', $id)
            ->firstOrFail();
        return $this->successData(compact("conquer"));

    }

    /**挑战编辑
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function editConquerRecord(Request $request, $id)
    {

        $conquer = UserConquer::query()
            ->where('id', $id)
            ->firstOrFail();
        return $this->successData(compact("conquer"));

    }


    /**
     * 更新活动
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function updateConquerRecord(Request $request, $id)
    {
        $motto = $request->input('motto');
        $weight = $request->input('weight');
        $cover = $request->input('cover');
        // 执行更新操作
        UserConquer::query()
            ->where('id', $id)
            ->update([
                'motto' => $motto,
                'weight' => $weight,
                'cover' => $cover
            ]);
        return $this->success(__('更新成功'));

    }


    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function delete(Request $request, $id)
    {
        $conquer = Conquer::query()->where('id', $id)->firstOrFail();

        if ($conquer->fragments()->exists()) {
            return $this->error(__('已有动态不能删除'));
        }
        DB::transaction(function () use ($id, $conquer) {
            $conquer->delete();
            $conquer->users()->detach();
        });

        return $this->success(__('删除成功'));
    }


    /**
     * 更新活动
     * @param ConquerRequest $request
     * @param $id
     * @return JsonResponse
     */
    public function update(ConquerRequest $request, $id)
    {
        $data = $request->filldata();
        $conquer = Conquer::query()->where('id', $id)->firstOrFail();
        $conquer->fill($data)->save();

        return $this->success(__('更新活动成功'));

    }

    /**
     * 挑战下的碎片详情
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function fragment(Request $request, $id)
    {

        $size = $request->input('size', 10);
        $fragments = WeightFragment::query()
            ->with(['images', 'videos'])
            ->where('conquer_id', $id)
            ->orderByDesc('created_at')
            ->paginate($size);
        //发布的人
        $users = User::query()
            ->whereIn('id', array_column($fragments->items(), 'user_id'))
            ->select(['id', 'nick_name', 'avatar', 'mobile'])
            ->get()
            ->keyBy('id');
        return $this->successData(compact('fragments', 'users'));

    }


    /**
     * 加入挑战列表
     * @param Request $request
     * @return JsonResponse
     */
    public function attend(Request $request, $id)
    {

        $userId = $this->id();
        $motto = $request->input('motto');
        $weight = $request->input('weight');
        $conquer = Conquer::query()->where('id', $id)->first();

        if ($conquer->has_started) {
            return $this->error(__('挑战已经开始不能再参加'));
        }
        // 检查关联是否已存在
        if (!$conquer->users()->where('user_id', $userId)->exists()) {
            $conquer->users()->attach($userId, ['motto' => $motto, 'weight' => $weight]);
            $conquer->increment('user_count');
        } else {
            return $this->error(__('已经加入过'));
        }

        return $this->success(__('加入成功'));
    }


    /**
     * 退出挑战
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function quit(Request $request, $id)
    {
        $userId = $this->id();
        $conquer = Conquer::query()->where('id', $id)->first();

        // 检查关联是否存在
        if ($conquer->users()->where('user_id', $userId)->exists()) {
            // 如果关联存在，则执行 detach() 方法
            $conquer->users()->detach($userId);
            $conquer->decrement('user_count');
            return $this->success(__('退出成功'));
        } else {
            // 如果关联不存在，你可以根据需要执行适当的操作，比如提示用户或者执行其他操作
            return $this->error(__('您已经退出过'));
        }


    }

    /**
     * 更新挑战的背景
     * @param ConquerBgImageRequest $request
     * @return JsonResponse
     */
    public function changeBg(ConquerBgImageRequest $request)
    {
        $data = $request->filldata();
        $url = $data['url'];
        $conquerId = $data['conquer_id'];
        $conquer = Conquer::query()->where('id', $conquerId)->first();
        //删除阿里云的数据
        $path = $conquer['thumb'];
        $url && Storage::disk('oss')->delete(substr($path, strrpos($path, "conquer"), strlen($path) - strrpos($path, "conquer")));
        $conquer->update(['thumb' => $url]);
        return $this->successData(compact('url'));


    }

    /**
     * 获取用户最后的体重
     * @param Request $request
     * @return JsonResponse
     */
    public function latest(Request $request, $conquerId)
    {

        $userId = $this->id();
        $fragment = WeightFragment::query()
            ->with(['conquer'])
            ->when($conquerId, function ($query) use ($conquerId) {
                $query->where('conquer_id', $conquerId);
            })
            ->where('user_id', $userId)
            ->latest()
            ->first();
        if ($fragment) {
            $weight = $fragment->weight;
        } else {
            $conquer = UserConquer::query()
                ->where('conquer_id', $conquerId)
                ->where('user_id', $userId)->first();
            $weight = $conquer->weight;
        }
        return $this->successData(compact('weight'));

    }

    function punch(Request $request, $conquerId)
    {
        $date = $request->input('date');
        $userId = $request->input('user_id');
        // 如果没有传递日期，则使用当前日期
        $date = $date ? Carbon::parse($date) : Carbon::now();

        // 获取传递日期所在月份的开始和结束时间
        $startOfMonth = $date->startOfMonth()->toDateTimeLocalString();
        $endOfMonth = $date->endOfMonth()->toDateTimeLocalString();

        $dates = WeightFragment::query()
            ->where('conquer_id', $conquerId)
            ->where('user_id', $userId)
            ->whereBetween('created_at', [$startOfMonth, $endOfMonth])
            ->get()
            ->pluck('created_at');

// 如果需要将日期字符串格式化为特定格式的字符串
        $dates = $dates->map(function ($date) {
            // 格式化为特定格式，例如 'Y-m-d'
            return date('Y-m-d', strtotime($date));
        });
        return $this->successData(compact('dates'));
    }

    public function notice($conquerId)
    {
        $conquer = Conquer::query()->where('id', $conquerId)->first();
        $users= Socialite::query()->whereIn('user_id',$conquer->users()->pluck('users.id')->toArray())->get();
        $app = WechatMini::getInstance();
        foreach ($users as $user )
        {
            $result = $app->subscribe_message->send([
                'touser' => $user->app_user_id,
                'template_id' => 'TJmlYKB_ncZ0ddRd71K92w1dGq1RvEE7v1aHzba-eIA',
                'page' => '/Conquer/Detail?id=' . $conquerId,
                'data' => [
                    'thing1' => [
                        'value' => $conquer->title."活动已开始",
                    ],
                    'time2' => [
                        'value' => $conquer->start_at,
                    ],
                ],

            ]);
        }

        return $this->success('发送成功');
    }


}
